package Servlet;

import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/blogDelete")
public class BlogDeleteServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user=Util.checkLogin(req);
        if(user==null){
            resp.sendRedirect("blog_login.html");
            return;
        }

        String blogId=req.getParameter("blogId");
        if(blogId==null||blogId.equals("")){
            String html="<h3>当前删除的文章ID缺失!</h3>";
            resp.getWriter().write(html);
            return;
        }
        BlogDao blogDao=new BlogDao();
        Blog blog=blogDao.selectOne(Integer.parseInt(blogId));
        if(blog==null){
            String html="<h3>当前删除的文章不存在!</h3>";
            resp.getWriter().write(html);
            return;
        }

        if(blog.getUserId()!=user.getUserId()){
            String html="<h3>无权删除别人博客！</h3>";
            resp.getWriter().write(html);
            return;
        }
        blogDao.delete(Integer.parseInt(blogId));
        resp.sendRedirect("blog_list.html");
    }
}
